# -*- coding: utf-8 -*-
'''
Copyright(C) 2013 "Kevin Xu <ssonxu@gmail.com>"

This file is part of acqu-center.

acqu-center is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

acqu-center is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with acqu-center.  If not, see <http://www.gnu.org/licenses/>.
'''
import os
import jinja2
import logging
import urllib

from google.appengine.api import users

from modules.box import Value 
from modules.box import Box
from modules.box import Stuff

from modules.contact import Contact as Con

from modules.Predef import Predef as PRE
from modules.parser import parser as ROCK

class Cell:
        
    ####################################################
    # Initialize
    ####################################################
    def __init__(self,context):
        self.context=context
        self.message=''
        self.errmessage=''

        self.user = Con.addUser(users.get_current_user().email())

        ID=self.context.request.get('ID')
        if ID !='':
            self.b = Box.getBoxByID(int(ID))
        else:
            la=urllib.unquote(self.context.request.get('label'))
            if la != '':
                self.b = Box.getBox(la)
                if not self.b:
                    self.b = Box(label=la) 
                    self.b.stuffs = []
                    self.MESSAGE("Creating a new box...")
            else:
                self.ERRMESSAGE("IMPOSSIBLE!!!Empty box!!!")


    ####################################################
    # For message
    ####################################################
    def MESSAGE(self,m):
        self.message=PRE.genMessage(self.message,m)

    def ERRMESSAGE(self,m):
        self.errmessage=PRE.genMessage(self.errmessage,"ERROR:"+m)

    ####################################################
    # Show the content
    ####################################################
    def getContent(self, t):

        st_new=Stuff( pattern='', message=self.context.request.get('message'),
                expression=self.context.request.get('lambda') , p1=self.context.request.get('p1'),
                    p2=self.context.request.get('p2'), val=[Value(val='0')])

        temp_path=os.path.join(
                os.path.dirname(__file__),
                "../templates/")

        temp=jinja2.Environment(loader=jinja2.FileSystemLoader(temp_path)).get_template(t)

        user = users.get_current_user()
        u = '%s <a href="%s"> sign out </a>' % (user.nickname(), users.create_logout_url("/"))

        return temp.render(
                {
                    'doors':PRE.doors,
                    'user': u,
                    'b':self.b,
                    'e':self.errmessage,
                    'm':self.message,
                    'n':st_new,
                    'isAdmin':users.is_current_user_admin(),
                    })

    ####################################################
    # Read and Check settings to GET
    ####################################################
    def doGet(self):
        self.context.response.out.write(self.getContent('editsetting.html'))

    ####################################################
    # Read and Check settings to POST
    ####################################################
    def doPost(self):

        self.b.url=self.context.request.get('url')
        self.b.description=self.context.request.get('des')

        # update the current settings
        for k in self.b.stuffs:
            ID=k.ID()
            k.pattern=self.context.request.get('pattern_'+ID)
            k.expression=self.context.request.get('lambda_'+ID)
            k.message=self.context.request.get('message_'+ID)
            k.p1=self.context.request.get('p1_'+ID)
            k.p2=self.context.request.get('p2_'+ID)

        # check deleted item
        # TODO: It would be a issue if we deleted many items together. 
        # because remove a element in a for loop
        for k in self.b.stuffs:
            ID=k.ID()
            if self.context.request.get('hidden_'+ID) == 'Deleted':
                self.b.stuffs.remove(k)
                #logging.info("<{}> has been deleted!".format(k) )
                self.MESSAGE('Success: <{}> has been deleted!'.format(ID))

        # add a new item
        if self.context.request.get('pattern')!='':
            st=Stuff( itemID=PRE.getTimeStamp(), pattern=self.context.request.get('pattern'), message=self.context.request.get('message'),
                expression=self.context.request.get('lambda') , p1=self.context.request.get('p1'),
                    p2=self.context.request.get('p2'), val=[Value(val='0')])

            self.b.stuffs.append(st)

        self.MESSAGE(u'Success: The new data has been updated!')
        ROCK(self.b).run()
        self.MESSAGE(u'Report:{}'.format(self.b.report(isHTML=True)))

        if self.context.request.get('Update'):
            self.b.put()
            self.context.response.out.write(self.getContent('editsetting.html'))
        else:
            if self.b.isRunning:
                self.b.drawbackIt()
            else:
                self.b.lauchIt()
            self.context.redirect('/')
